package com.jdls.tanhua.dubbo.impl;

import com.jdls.tanhua.dubbo.FriendApi;
import com.jdls.tanhua.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 嘉德罗斯
 * @date 2021/10/28
 */
@DubboService
public class FriendImpl implements FriendApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List<Friend> findAll(Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        List<Friend> friends = mongoTemplate.find(query, Friend.class);

        return friends;
    }

    @Override
    public List<Friend> findAll(Long userId, Integer page, Integer pagesize) {
        Query query = Query.query(Criteria.where("userId").is(userId)).with(Sort.by(Sort.Order.desc("cre")))
                .skip((page-1)*pagesize).limit(pagesize);
        List<Friend> friends = mongoTemplate.find(query, Friend.class);

        return friends;
    }

    @Override
    //添加好友
    public boolean save(Long id, Long userId) {

        try {
            Query query = Query.query(Criteria.where("userId").is(id).and("friendId").is(userId));
            Friend friend = mongoTemplate.findOne(query, Friend.class);
            if (friend == null){
                friend = new Friend();
                friend.setCreated(System.currentTimeMillis());
                friend.setFriendId(userId);
                friend.setUserId(id);
                mongoTemplate.insert(friend);
            }

            Query q = Query.query(Criteria.where("userId").is(userId).and("friendId").is(id));
            friend = mongoTemplate.findOne(q, Friend.class);
            if (friend == null){
                friend = new Friend();
                friend.setCreated(System.currentTimeMillis());
                friend.setFriendId(id);
                friend.setUserId(userId);
                mongoTemplate.insert(friend);
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
